<template>
	<view>
		<view :style="[{background:themeConfig.primaryColor}]">
			<view class="padding-sm margin-left-xs margin-right-xs" :style="[{color:themeConfig.commonColor}]">
				<view class="flex justify-between">
					<view class="flex justify-content align-center">
						<input style="width: 360rpx" class="text-xl" :value="deviceName" :focus="focusDeviceName"
							@input='changeDeviceNameInput' />
						<view
							:class="[isChangeDeviceName && changeDeviceName != deviceName ? 'cuIcon-roundcheckfill' : 'cuIcon-writefill']"
							class="margin-left-xs" style="font-size: 50rpx;"
							@tap="isChangeDeviceName && changeDeviceName != deviceName ? updateDeviceName() : getFocus()">
						</view>
					</view>
					<view class="flex justify-content align-center">
						<view class="cu-avatar round lg light bg-white">
							<signal :netSignal="netSignal"></signal>
						</view>
						<view class="cu-avatar round lg light bg-white margin-left">
							<surplus2 :status="status" :charging="charging" :surplus="surplus"></surplus2>
						</view>
					</view>
				</view>
				<view class="flex justify-between padding-top">
					<view class="flex">
						<view class="text-sm" @longpress="copyDeviceCore">
							{{$t('deviceCore')}}:{{deviceCore}}
						</view>
						<view class="cuIcon-copy margin-lr-xs" style="font-size: 35rpx;" @tap="copyDeviceCore">
						</view>
					</view>
					<view class="text-sm">{{$t('cardNumber')}}:<text class="text-cut">{{phoneNumber}}</text>
					</view>
				</view>
				<view class="flex justify-between padding-top">
					<view class="text-sm">{{$t('product')}}:{{product}}</view>
					<view class="text-sm">{{$t('series')}}:{{series}}</view>
				</view>
				<view class="flex justify-between padding-top">
					<view class="text-sm">{{$t('hardware')}}{{$t('version')}}:{{hardVersion}}</view>
					<view class="text-sm">{{$t('software')}}{{$t('version')}}:{{softVersion}}</view>
				</view>
				<view class="text-sm padding-top">{{$t('address')}}:{{address}}</view>
				<!-- <view class="text-sm padding-top">{{$t('company')}}:{{companyName}}</view> -->
				<view class="flex justify-between padding-top" v-if="status==='ONLINE'">
					<view class="text-sm">{{$t('ONLINE')+$t('time')}}:{{lastOnLineTimer}}</view>
					<view class="text-sm">{{$t('OFFLINE')+$t('count')}}:{{offLineNum}}</view>
				</view>
				<view v-else class="flex justify-between padding-top">
					<view class="text-sm">{{$t('OFFLINE')+$t('time')}}:{{lastOffLineTimer}}</view>
					<view class="text-sm">{{$t('OFFLINE')+$t('count')}}:{{offLineNum}}</view>
				</view>
				<view class="flex justify-between align-center padding-top">
					<view class="text-cut text-center">
						<view class="text-sm">{{$t('status')}}</view>
						<view class="text-xl padding-top-sm">{{status}}</view>
					</view>
					<view class="text-cut text-center">
						<view class="text-sm">{{$t('sensor')}}</view>
						<view class="text-xl padding-top-sm">{{explainCount}}</view>
					</view>
					<view v-if="netSignal === 255" class="text-cut text-center">
						<view class="text-sm">{{$t('setting')}}</view>
						<view class="text-xl padding-top-sm">{{settingCount}}</view>
					</view>
					<view v-else class="text-cut text-center">
						<view class="text-sm">{{$t('signal')}}(dBn)</view>
						<view class="text-xl padding-top-sm">{{netSignal}}</view>
					</view>
					<view v-if="surplus === 255" class="text-cut text-center">
						<view class="text-sm">{{$t('param')}}</view>
						<view class="text-xl padding-top-sm">{{paramCount}}</view>
					</view>
					<view v-else class="text-cut text-center">
						<view class="text-sm">{{$t('surplus')}}(%)</view>
						<view class="text-xl padding-top-sm">{{surplus}}</view>
					</view>
					<view class="text-cut text-center" @tap="gotoCardInfo">
						<view class="text-sm">{{$t('card')}}{{$t('status')}}</view>
						<view class="text-xl padding-top-sm">{{phoneStatus}}</view>
					</view>
				</view>
			</view>
		</view>

		<view :style="[{background:themeConfig.commonColor}]">
			<view :style="[{background:themeConfig.commonColor}]" class="padding-top-sm">
				<view class="flex justify-between align-center text-center">
					<view class="flex-sub margin-sm padding-tb common-box" @tap="refreshStatus">
						<view class="cuIcon-refresh text-bold" style="font-size: 40rpx;" :style="[{color:themeConfig.primaryColor}]"></view>
						<view class="padding-top-sm text-df">{{$t('refresh')}}</view>
					</view>
					<view class="flex-sub margin-sm padding-tb common-box" @tap="gotoDeviceStatus">
						<view class="cuIcon-order text-bold" style="font-size: 40rpx;" :style="[{color:themeConfig.primaryColor}]"></view>
						<view class="padding-top-sm text-df">
							{{$t('status')}}
						</view>
					</view>
					<view class="flex-sub margin-sm padding-tb common-box" @tap="deviceWarn">
						<view v-if="warnNum > 0" class="text-bold text-xl"  :style="[{color:themeConfig.primaryColor}]">
							{{warnNum}}
						</view>
						<view v-else class="cuIcon-warn text-bold" style="font-size: 40rpx;" :style="[{color:themeConfig.primaryColor}]">
						</view>
						<view class="padding-top-sm text-df">{{$t('warn')}}</view>
					</view>
					<view class="flex-sub margin-sm padding-tb common-box" @tap="deviceLocal">
						<view class="cuIcon-location text-bold" style="font-size: 40rpx;" :style="[{color:themeConfig.primaryColor}]">
						</view>
						<view class="padding-top-sm text-df">{{$t('location')}}</view>
					</view>
				</view>
			</view>

			<view v-if="weather && weather.weather && language=='zh'"
				class="flex justify-start padding-sm margin-sm common-box"
				:style="[{background:themeConfig.primaryColor}]">
				<image :src="weather.weatherImage" style="width: 120rpx;height: 120rpx" />
				<view class="text-white text-df">
					<view class="margin-bottom-xs text-sm">{{ weather.weather }} {{ weather.temperature }}°C</view>
					<view class="margin-bottom-xs text-sm">{{ weather.lowTemperature }}°C ~ {{ weather.highTemperature }}°C</view>
					<view class="text-sm">
						<text>{{ weather.winDirection }}</text>
						<text class="margin-left-sm">{{ weather.winGrade }}</text>
						<text class="margin-left-sm">{{ weather.winSpeed }}</text>
						<text class="margin-left-sm">{{ $t('air')}}{{$t('quality') }}:{{ weather.airQuality }}</text>
					</view>
				</view>
			</view>

			<view :style="[{background:themeConfig.commonColor}]" class="padding-top-sm">
				<view class="flex justify-between align-center text-center">
					<view class="flex-sub margin-sm padding-tb common-box">
						<switch :class="[themeConfig.theme,follow?'checked':'']" :checked="follow"
							@change="followChange">
						</switch>
						<view class="padding-top-sm text-df">{{$t('focus')}}</view>
					</view>
					<view class="flex-sub margin-sm padding-tb common-box">
						<switch :class="[themeConfig.theme,canDeviceLinkage?'checked':'']" :checked="canDeviceLinkage"
							@change="linkageChange"></switch>
						<view class="padding-top-sm text-df">{{$t('linkage')}}</view>
					</view>
					<view class="flex-sub margin-sm padding-tb common-box">
						<switch :class="[themeConfig.theme,enable?'checked':'']" :checked="enable"
							@change="enableChange">
						</switch>
						<view class="padding-top-sm text-df">{{$t('enable')}}</view>
					</view>
					<view class="flex-sub margin-sm padding-tb common-box">
						<switch :class="[themeConfig.theme,openPush?'checked':'']" :checked="openPush"
							@change="openPushChange"></switch>
						<view class="padding-top-sm text-df">{{$t('push')}}</view>
					</view>
				</view>
			</view>

			<view class="margin-sm common-box" v-if="address && address!==''">
				<view class="cu-bar bg-white solid-bottom">
					<view class="action">
						<text class="cuIcon-titles text-orange"></text> {{$t('lock')}}{{$t('local')}}
					</view>
					<view class="action">
						<switch :class="[themeConfig.theme,lockLocal?'checked':'']" :checked="lockLocal"
							@change="lockLocalChange"></switch>
					</view>
				</view>
				<map :subkey="qqMapKey" v-if="isShowMap" id="myMap" class="margin-bottom-sm"
					style="height: 200rpx;width: 100%;" :scale="12" :longitude="lng" :latitude="lat" :markers="markers"
					@tap="mapTap"></map>
				<view class="flex">
					<view class="flex-sub padding-sm radius">
						<button class="cu-btn block margin-xs text-white" size="mini"
							:style="[{backgroundColor:themeConfig.primaryColor}]" @tap='tapMyLocation'>
							{{$t('my')}}{{$t('location')}}
						</button>
					</view>
					<view class="flex-sub padding-sm radius">
						<button class="cu-btn block margin-xs text-white" size="mini"
							:style="[{backgroundColor:themeConfig.primaryColor}]" @tap='tapSaveLocation'>
							{{$t('save')}}{{$t('location')}}
						</button>
					</view>
				</view>
			</view>
			<view class="margin-sm common-box" style="height: 800px;"
				v-if="childDeviceList && childDeviceList.length > 0">
				<view class="cu-bar bg-white solid-bottom">
					<view class="action">
						<text class="cuIcon-titles text-orange"></text> {{$t('child')+$t('device')}}
					</view>
				</view>
				<view style="position: relative;">
					<view style="position: absolute;left: 0;top: 0;">
						<device-list-item v-for="(item,index) in childDeviceList" :key="index" :device="item">
						</device-list-item>
					</view>
				</view>
			</view>

			<view class="cu-modal bottom-modal" :class="[showErrorModal?'show':'']">
				<view class="cu-dialog">
					<view class="cu-bar bg-white">
						<view class="action text-red" @tap="hideErrorModal">{{$t('close')}}</view>
					</view>
					<view class="padding-xl">
						{{settingError}}
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		showToast,
		showLoading,
		hideLoading,
		showModal
	} from '@/util/toast.js'
	import {
		formatDeviceStatus,
		formatPhoneStatus,
		copy
	} from '@/util/utils.js'
	import myConfig from '@/myConfig.js'
	import Surplus2 from '@/components/ztn-custom/Surplus2/index.vue'
	import Signal from '@/components/ztn-custom/Signal/index.vue'
	import {
		formatDateTime
	} from '@/util/formatTime.js'
	import * as iotDeviceApi from '@/api/iot/iotDeviceApi.js'
	import *
	as deviceSettingApi from '@/api/iot/iotDeviceSettingApi.js'
	import *
	as deviceSensorApi from '@/api/iot/iotDeviceSensorApi.js'
	import *
	as weatherApi from '@/api/common/commonWeatherApi.js'
	import DeviceListItem from '@/components/ztn-custom/DeviceListItem/index.vue'
	import * as storage from '@/util/storage.js'
	export default {
		name: 'DeviceInfo',
		data() {
			return {
				uniInterface: '',
				deviceName: 'xxxxxx',
				status: 'xx',
				charging: false,
				surplus: '0',
				netSignal: 'xx',
				phoneNumber: 'xx',
				product: 'xx',
				series: 'xx',
				address: 'xxxxxxx',
				companyName: 'xxx',
				hardVersion: '',
				softVersion: '',
				offLineNum: '',
				warnNum: '',
				lastOffLineTimer: '',
				lastOnLineTimer: '',
				focusDeviceName: false,
				changeDeviceName: '',
				isChangeDeviceName: false,
				showErrorModal: false,
				settingError: '',
				sensorList: [],
				openBind: false,
				lockLocal: false,
				openPush: false,
				enable: false,
				follow: false,
				canDeviceLinkage: false,
				lat: null,
				lng: null,
				isShowMap: false,
				markers: [],
				weather: null,
				sensorCount: 0,
				settingCount: 0,
				explainCount: 0,
				paramCount: 0,
				phoneStatus: '',
				language: storage.getLanguage(),
				showChildDevice: storage.getShowChildDevice(),
				childDeviceList: [],
				qqMapKey: myConfig.app.qqMapKey
			}
		},
		props: {
			deviceCore: {
				type: String,
				default: ''
			},
			value: {
				type: String,
			},
			keyName: {
				type: String,
			},
			port: {
				type: String,
			}
		},
		computed: {
			themeConfig() {
				return this.$store.state.themeConfig
			}
		},
		mounted() {
			this.init()
			storage.setDeviceNavigationComponent('deviceInfo')
		},
		methods: {
			listDeviceBindChildDevice() {
				if (this.showChildDevice !== '1') {
					this.childDeviceList = []
					return
				}
				iotDeviceApi.listDeviceBindChildDevice({
					parentDeviceCore: this.deviceCore
				}).then(res => {
					const {
						data
					} = res
					if (data) {
						this.childDeviceList = data
					}
				})
			},
			gotoCardInfo() {
				uni.navigateTo({
					url: `/pages/cardInfo/cardInfo?iccid=${this.phoneNumber}`
				})
			},
			getWeather() {
				weatherApi.getWeather({
					deviceCore: this.deviceCore
				}).then(res => {
					const {
						data
					} = res
					this.weather = data
				})
			},
			tapSensor(e) {
				const {
					sensorId,
					sensorName,
					deviceCore,
					port
				} = e
				const deviceName = this.deviceName
				uni.navigateTo({
					url: `/pages/deviceSensorData/deviceSensorData?sensorId=${sensorId}&sensorName=${sensorName}&deviceCore=${deviceCore}&deviceName=${deviceName}&port=${port}`
				})
			},
			getListWith() {
				deviceSensorApi.getListWith({
					deviceCore: this.deviceCore,
					withExplain: true,
					withParam: true,
					withSetting: true,
				}).then(res => {
					const {
						data
					} = res
					if (data) {
						this.sensorList = data
						let sensorCount = 0
						let explainCount = 0
						let paramCount = 0
						let settingCount = 0
						data.forEach(sensor => {
							sensorCount = sensorCount + 1
							sensor.paramList.forEach(param => {
								paramCount = paramCount + 1
							})
							sensor.settingList.forEach(setting => {
								settingCount = settingCount + 1
								if (setting.keyName === this.keyName && setting.port === this
									.port) {
									this.executeCommand(setting.name)
								}
							})
							sensor.explainList.forEach(explain => {
								explainCount = explainCount + 1
							})
						})
						this.sensorCount = sensorCount
						this.explainCount = explainCount
						this.paramCount = paramCount
						this.settingCount = settingCount
					}
				})
			},
			executeCommand(settingName) {
				const confirmText = this.$t('confirm')
				showModal(this.$t('cancel'),
					`${this.$t('showModalPort')}:${this.port} ${settingName} ${this.value}`, '', true,
					confirmText, cancelText, (res) => {
						deviceSettingApi.sendSetting({
							deviceCore: this.deviceCore,
							value: this.value,
							keyName: this.keyName,
							port: this.port
						}).then((res) => {
							if (res.data) {
								showToast(this.$t('success'), 'none', 1000, false)
							}
						})
					}, (res) => {
						return
					})
			},
			getDeviceDetails() {
				iotDeviceApi.getDeviceDetails({
					deviceCore: this.deviceCore
				}).then((res) => {
					if (res.data) {
						const data = res.data
						this.uniInterface = data.uniInterface || null
						const latLng = {
							lat: data.lat,
							lng: data.lng,
						}
						this.lat = latLng.lat
						this.lng = latLng.lng
						this.lockLocal = data.lockLocal
						this.follow = data.follow
						this.canDeviceLinkage = data.canDeviceLinkage
						this.openPush = data.openPush
						this.enable = data.enable
						this.deviceName = data.deviceName
						this.status = formatDeviceStatus(this, data.status)
						this.charging = data.charging
						this.warnNum = data.warnNum || this.$t('unKnow')
						this.surplus = data.surplus
						this.netSignal = data.netSignal
						this.product = data.product
						this.series = data.series
						this.phoneNumber = data.phoneNumber || this.$t('unKnow')
						this.address = data.address || this.$t('unKnow')
						this.companyName = data.companyName
						this.hardVersion = data.hardVersion || this.$t('unKnow')
						this.softVersion = data.softVersion || this.$t('unKnow')
						this.offLineNum = data.offLineNum || this.$t('unKnow')
						this.phoneStatus = formatPhoneStatus(this, data.phoneStatus) || this.$t('unKnow')
						this.lastOffLineTimer = formatDateTime(data
							.lastOffLineTimer, this.$t('unKnow'))
						this.lastOnLineTimer = formatDateTime(data
							.lastOnLineTimer, this.$t('unKnow'))
						this.makeMarker()
						this.isShowMap = true


					}
				})
			},
			init() {
				this.getDeviceDetails()
				this.getListWith()
				this.getWeather()
				this.listDeviceBindChildDevice()
			},
			hideErrorModal() {
				this.showErrorModal = false
			},
			refreshStatus() {
				showLoading(this.$t('loading'), false)
				iotDeviceApi.refreshStatus({
					deviceCore: this.deviceCore,
				}).then((res) => {
					hideLoading()
					this.init()
				})
			},
			gotoDeviceStatus() {
				uni.navigateTo({
					url: `/pages/deviceStatus/deviceStatus?deviceName=${this.deviceName}&deviceCore=${this.deviceCore}`
				})
			},
			deviceWarn() {
				uni.navigateTo({
					url: `/pages/deviceWarn/deviceWarn?deviceName=${this.deviceName}&deviceCore=${this.deviceCore}`
				})
			},
			deviceLocal() {
				uni.navigateTo({
					url: `/pages/deviceLocal/deviceLocal?deviceName=${this.deviceName}&deviceCore=${this.deviceCore}`,
				})
			},
			getFocus() {
				this.focusDeviceName = true
			},
			changeDeviceNameInput(e) {
				this.isChangeDeviceName = true
				this.changeDeviceName = e.detail.value
			},
			updateDeviceName(e) {
				const deviceName = this.changeDeviceName
				if (deviceName == '') {
					showToast(this.$t('not') + this.$t('data'), 'none', 1000, false)
					return
				}
				iotDeviceApi.updateDeviceInfo({
					deviceCore: this.deviceCore,
					deviceName: deviceName
				}).then((res) => {
					if (res.data) {
						this.deviceName = deviceName
						this.focusDeviceName = false
						this.isChangeDeviceName = false
						this.changeDeviceName = ''
						showToast(this.$t('success'), 'none', 1000, false)
					}
				})
			},
			followChange() {
				this.follow = !this.follow
				iotDeviceApi.updateDeviceInfo({
					deviceCore: this.deviceCore,
					follow: this.follow
				}).then((res) => {
					if (res.data) {
						showToast(this.$t('success'), 'none', 1000, false)
					}
				})
			},
			linkageChange() {
				this.canDeviceLinkage = !this.canDeviceLinkage
				iotDeviceApi.updateDeviceInfo({
					deviceCore: this.deviceCore,
					canDeviceLinkage: this.canDeviceLinkage
				}).then((res) => {
					if (res.data) {
						showToast(this.$t('success'), 'none', 1000, false)
					}
				})
			},
			lockLocalChange() {
				this.lockLocal = !this.lockLocal
				iotDeviceApi.updateDeviceInfo({
					deviceCore: this.deviceCore,
					lockLocal: this.lockLocal
				}).then((res) => {
					if (res.data) {
						showToast(this.$t('success'), 'none', 1000, false)
					}
				})
			},
			makeMarker() {
				const marker = {
					width: 25,
					height: 25,
					latitude: this.lat,
					longitude: this.lng,
					iconPath: `${myConfig.app.baseUrl}/file/download/static/iot/uni/map/numsImage/${this.$store.state.themeConfig.theme}/marker.png`,
					label: {
						width: 180,
						height: 25,
						// borderWidth: 1,
						borderRadius: 5,
						color: '#FFF',
						bgColor: this.$store.state.themeConfig.primaryColor,
						content: this.deviceName
					}
				}
				this.markers = [marker]
			},
			tapMyLocation() {
				this.lat = storage.getLat() || 27.099994
				this.lng = storage.getLng() || 114.324520
				this.makeMarker()
			},
			mapTap(e) {
				this.lat = e.detail.latitude
				this.lng = e.detail.longitude
				this.makeMarker()
			},
			tapSaveLocation() {
				iotDeviceApi.updateDeviceInfo({
					deviceCore: this.deviceCore,
					lat: this.lat,
					lng: this.lng,
				}).then((res) => {
					if (res.data) {
						showToast(this.$t('success'), 'none', 1000, false)
					}
				})
			},
			enableChange() {
				this.enable = !this.enable
				iotDeviceApi.setEnable({
					deviceCore: this.deviceCore,
					enable: this.enable
				}).then((res) => {
					if (res.data) {
						showToast(this.$t('success'), 'none', 1000, false)
					}
				})
			},
			openPushChange() {
				this.openPush = !this.openPush
				iotDeviceApi.updateDeviceInfo({
					deviceCore: this.deviceCore,
					openPush: this.openPush
				}).then((res) => {
					if (res.data) {
						showToast(this.$t('success'), 'none', 1000, false)
					}
				})
			},
			copyDeviceCore() {
				copy(this, this.deviceCore)
			},
		},
		components: {
			Signal,
			Surplus2,
			DeviceListItem
		}
	}
</script>
